<template>
  <div class="informationBox">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-select filterable v-model="formInline.stoIdBig" placeholder="请选择仓库" @change="getCkId">
          <el-option v-for="(item, index) in wareHouseDataBig" :key="index" :value="item.stoId" :label="item.stoName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select clearable filterable v-model="formInline.stoAreaIdBig" placeholder="请选择货区" @change="getHuoQu">
          <el-option v-for="(item, index) in wmsData" :key="index" :value="item.stoAreaId" :label="item.stoAreaName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select clearable multiple filterable v-model="formInline.stoAreaId" placeholder="请选择剂型" @change="changeHQ">
          <el-option v-for="(item, index) in informationData" :key="index" :value="item.id"
            :label="item.formulationName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="formInline.stoUnitCode" placeholder="请输入货位代码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-circle-plus-outline" v-hasPermi="['index:position:add']"
          @click="add('add')">新增</el-button>
        <el-button type="primary" icon="el-icon-circle-plus-outline" v-hasPermi="['index:position:add']"
          @click="addLayerNum">续增</el-button>
        <el-button type="primary" icon="el-icon-search" v-hasPermi="['index:position:query']"
          @click="getLocationList">查询</el-button>
        <el-button type="primary" icon="el-icon-printer" v-hasPermi="['index:position:print']"
          @click="printCode">打印</el-button>
        <el-button type="primary" icon="el-icon-video-pause" v-hasPermi="['index:position:stateAllEdit']"
          @click="start">批量开启</el-button>
        <el-button type="primary" icon="el-icon-video-pause" v-hasPermi="['index:position:stateAllEdit']"
          @click="stop">批量停用</el-button>
        <el-button type="danger" icon="el-icon-refresh" @click="cancelValidateForm">重置</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="del">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="locationList" border @selection-change="handleSelectionChange" height="605px">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" align="center"> </el-table-column>
      <el-table-column prop="stoUnitCode" label="货位code" width="180" align="center"></el-table-column>
      <el-table-column prop="stoName" label="所属仓库" width="180" align="center"></el-table-column>
      <el-table-column prop="stoAreaName" label="所属库区" align="center"></el-table-column>
      <el-table-column prop="enableState" label="是否启用" align="center">
        <template slot-scope="scope">
          <el-switch :value="scope.row.enableState" active-color="#13ce66" inactive-color="#ff4949" :active-value="'1'"
            v-hasPermi="['index:position:stateEdit']" :inactive-value="'0'" @change="toggleState(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-delete" @click="singleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 续增 -->
    <el-dialog title="续增" :visible.sync="dialogVisible" width="50%" @close="handleClose">
      <el-row :gutter="15">
        <el-form ref="formRef" :model="formData" size="medium" label-width="100px" :rules="rules">
          <el-col :span="12">
            <el-form-item label="货位选择" prop="stoUnitCode">
              <el-select filterable v-model="formData.stoUnitCode" placeholder="请选择需要续增的货位" clearable
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in allCodeAdd" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="enableState">
              <el-switch v-model="formData.enableState" active-text="启用" inactive-text="停用" :active-value="'1'"
                :inactive-value="'0'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增加个数" prop="number">
              <el-input v-model="formData.number" placeholder="请输入增加的个数"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
    <el-pagination background layout="total, prev, pager, next, sizes,jumper" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="formInline.pageNum" :page-size="formInline.pageSize"
      :page-sizes="[20, 50, 100, 500]" :total="total">
    </el-pagination>
    <!-- 新增货位 -->
    <addLocation ref="addLocationRef" :visible.sync="visible" @addSuccess="addSuccess"></addLocation>
    <!-- 货位打印 -->
    <locationPrint v-show="false" ref="locationPrintRef"></locationPrint>
  </div>
</template>

<script>
  import {
    locationOperation,
    updateBasicStoUnitEnableStatusAll, //批量更改状态
    updateBasicStoUnitEnableStatus, //更改状态
    printStoUnit, //打印
    getAllStoUnitCode, //层位数下拉
    addStoUnitStorage, //层位数提交
    batchDeleteByStoUnitId, //删除
    deleteByStoUnitId //单独删除
  } from "@/api/index/warehouse";
  import {
    findStoAreaAllOne,
    findAllBasicStoStockData, //货区获取
    getAllWarehouseList, //仓库下拉
  } from "@/api/index/yxl.js"
  import addLocation from './addLocation/index.vue'
  // import locationPrint from '@/views/basic/print/locationPrint.vue'
  import locationPrint from '@/views/basic/print/locationList/locationPrint.vue'
  export default {
    data() {
      return {
        wmsData: [], //货区
        locationList: [],
        visible: false,
        formInline: {
          pageSize: 20,
          stoUnitCode: '',
          stoAreaId: [],
          pageNum: 1
        },
        total: 0,
        informationData: [],
        wareHouseDataBig: [], //仓库
        toAeraId: '',
        toStoId: '',
        selectData: [], //批量选中的数据
        printDataList: [], //打印的数据
        dialogVisible: false, //续增弹框显示
        allCodeAdd: [], //select续增下拉框数据
        formData: {
          number: null,
          stoUnitCode: '',
          enableState: '0'
        },
        rules: {
          stoUnitCode: [{
            required: true,
            message: '请选择货位code',
            trigger: 'change'
          }],
          enableState: [{
            required: true,
            message: '请选择启用状态',
            trigger: 'change'
          }],
          number: [{
            required: true,
            message: '请输入个数',
            trigger: 'blur'
          }]
        }
      }
    },
    components: {
      addLocation,
      locationPrint
    },
    created() {
      this.getSelect(); //仓库下拉
    },
    methods: {
      //仓库下拉获取
      getSelect() {
        getAllWarehouseList().then(res => {
          this.wareHouseDataBig = res.data;
          this.formInline.stoIdBig = res.data[0].stoId;
          this.getWms(this.formInline.stoIdBig);
        })
      },
      // 仓库切换
      getCkId(val) {
        this.formInline.stoIdBig = val; //仓库
        this.formInline.stoAreaIdBig = ''; //货区
        this.formInline.stoAreaId = []; //剂型
        this.wmsData = []; // 清空货区数据
        this.informationData = []; // 清空剂型数据
        this.getWms(this.formInline.stoIdBig); //获取货区
        this.getLocationList();
      },

      //货区切换
      getHuoQu(val) {
        this.formInline.stoAreaIdBig = val;
        this.formInline.stoAreaId = []; // 清空已选剂型
        if (val) {
          this.getWareArea(val); // 只有选择了货区才获取剂型
        } else {
          this.informationData = []; // 如果没有选择货区，清空剂型数据
        }
        this.getLocationList(); // 刷新列表
      },

      //获取剂型
      getWareArea(stoAreaId) {
        if (!stoAreaId) {
          this.informationData = [];
          return;
        }
        let param = {
          stoAreaId: stoAreaId
        };
        findStoAreaAllOne(param).then(res => {
          this.informationData = res || [];
          this.getLocationList();
        }).catch(() => {
          this.informationData = [];
        });
      },
      // 修改剂型方法
      changeHQ(val) {
        this.formInline.stoAreaId = val;
        this.getLocationList(); // 如果需要立即刷新数据
      },
      getWms(data) {
        findAllBasicStoStockData({
          stoId: data
        }).then(res => {
          this.wmsData = res;
          if (this.wmsData.length > 0) {
            this.formInline.stoAreaIdBig = res[0].stoAreaId;
            this.getWareArea(this.formInline.stoAreaIdBig);
          }
        }).catch(error => {
          console.error('获取仓库数据失败:', error);
          this.$message.error('获取仓库数据失败');
        });
      },
      //单独删除货位
      singleDel(row) {
        this.$confirm(`确认要进行删除吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteByStoUnitId({
            stoUnitId: row.stoUnitId
          }).then(res => {
            this.$message.success(res.msg);
            this.getLocationList();
          })
        })
      },
      //删除
      del() {
        if (this.selectData.length === 0) {
          this.$message.error("请至少选择一项");
          return;
        }
        this.$confirm(`确认要进行删除吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchDeleteByStoUnitId(this.selectData).then(res => {
            this.$message.success(res.msg);
            this.getLocationList();
          })
        })
      },
      //续增提交
      submit() {
        this.formData.stoId = this.formInline.stoIdBig;
        this.formData.stoAreaId = this.formInline.stoAreaIdBig;
        this.formData.dosageId = Array.isArray(this.formInline.stoAreaId) ? this.formInline.stoAreaId.join(',') : this
          .formInline.stoAreaId;//剂型
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            addStoUnitStorage(this.formData).then(res => {
              this.$message.success(res.msg);
              this.getLocationList();
              this.handleClose();
            })
          }
        })
      },
      //续增关闭
      handleClose() {
        this.dialogVisible = false;
        this.$nextTick(() => {
          this.$refs.formRef.resetFields();
        })
      },
      //层位数下拉框数据
      getAllCode() {
        let params = {
          stoId: this.formInline.stoId,
        }
        getAllStoUnitCode(params).then(res => {
          this.allCodeAdd = res.data;
        })
      },
      //续增操作
      addLayerNum() {
        // 验证剂型是否已选择
        if (!this.formInline.stoAreaId || this.formInline.stoAreaId.length === 0) {
          this.$message.warning('请先选择剂型');
          return;
        }
        this.dialogVisible = true;
        this.getAllCode(); //select续增数据
      },
      //打印
      printCode() {
        printStoUnit(this.selectData).then(res => {
          if (res.code == 200) {
            this.printDataList = res.data;
            this.$nextTick(() => {
              this.$refs.locationPrintRef.print(this.printDataList);
            })
          }
        })
      },
      // 任务状态修改
      toggleState(row) {
        // 临时保存当前状态，以便取消时恢复
        const currentState = row.enableState;
        // 根据 enableState 判断是启用还是停用
        let text = row.enableState === "1" ? "停用" : "启用";
        let query = {
          enableState: currentState === "1" ? "0" : "1", // 状态切换：如果是 "0"（禁用），则切换为 "1"（启用）；反之亦然
          stoUnitId: row.stoUnitId,
          stoUnitCode: row.stoUnitCode
        }
        // 弹出确认框
        this.$confirm(`确认要${text}此项任务吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 更新状态
          updateBasicStoUnitEnableStatus(query).then(res => {
            // 显示成功消息
            this.$message({
              type: 'success',
              message: `${text}成功!` // 根据操作状态来动态显示消息
            });
            // 更新列表或者执行其他操作（例如刷新数据等）
            this.getLocationList(); // 假设有一个方法用于刷新列表数据
          }).catch(error => {
            // 恢复原始状态
            row.enableState = currentState;
          });
        }).catch(() => {
          // 用户取消了操作，恢复原始状态
          this.$message({
            type: 'info',
            message: '操作已取消'
          });
          row.enableState = currentState; // 恢复原始状态
        });
      },

      //批量开启
      start() {
        if (this.selectData.length === 0) {
          this.$message.error("请至少选择一项");
          return;
        }
        let param = {
          status: 1
        };
        updateBasicStoUnitEnableStatusAll(this.selectData, param).then(res => {
          this.$message.success(res.msg);
          this.getLocationList();
        })
      },
      //获取多选数据
      handleSelectionChange(val) {
        this.selectData = val.map(item => item.stoUnitId);
      },
      //批量停用
      stop() {
        if (this.selectData.length === 0) {
          this.$message.error("请至少选择一项");
          return;
        }
        let param = {
          status: 0
        };
        updateBasicStoUnitEnableStatusAll(this.selectData, param).then(res => {
          this.$message.success(res.msg);
          this.getLocationList();
        })
      },
      // 仓库选择变化时触发
      handleWarehouseChange(val) {
        this.formInline.stoId = val;
        this.getWareArea();
      },
      handleSizeChange(newsize) {
        this.formInline.pageNum = 1;
        this.formInline.pageSize = newsize;
        this.getLocationList();
      },
      handleCurrentChange(newpage) {
        this.formInline.pageNum = newpage;
        this.getLocationList();
      },
      //获取货位
      getLocationList() {
        let params = {
          stoId: this.formInline.stoIdBig,//库房
          stoAreaId: this.formInline.stoAreaIdBig,//库区
          dosageId: Array.isArray(this.formInline.stoAreaId) ? this.formInline.stoAreaId.join(',') : this.formInline.stoAreaId,//剂型
          stoUnitCode: this.formInline.stoUnitCode,
          pageNum: this.formInline.pageNum,
          pageSize: this.formInline.pageSize,
        }
        locationOperation(params).then(res => {
          this.locationList = res.rows;
          this.total = res.total;
        })
      },
      // 新增成功后，刷新列表
      addSuccess() {
        this.getLocationList();
      },
      //新增数据
      add(item) {
        // 验证剂型是否已选择
        if (!this.formInline.stoAreaId || this.formInline.stoAreaId.length === 0) {
          this.$message.warning('请先选择剂型');
          return;
        }
        this.visible = true;
        this.$refs.addLocationRef.openDialog(item, this.formInline.stoAreaIdBig, this.formInline.stoAreaId);
      },
      //清空
      cancelValidateForm() {
        this.formInline.stoAreaId = [];
        this.formInline.stoUnitCode = '';
        this.getLocationList();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .informationBox {
    padding: 15px 0px 15px 15px;
  }

  .el-pagination {
    float: right;
    margin: 20px;
  }
</style>
